package com.modle.manage;
import java.lang.reflect.Proxy;
import java.util.Iterator;
import java.util.concurrent.ConcurrentMap;

import com.base.handle.ModleHandle;
import com.base.manage.BaseManage;
import com.hibernate.manage.tpl.InfDateManage;
import com.hibernate.manage.tpl.InfDateManageIfe;
import com.hibernate.modle.impl.TbUserModle;

public class ModleManage extends BaseManage implements Runnable{
	
	private Thread saveDbToMysql = new Thread(this);
	public ModleManage() {
    }
	
	public void InitThread() {
		saveDbToMysql.start();
	}

    public static ModleManage getInstance() {
        return SingletonFactory.instance;
    }
    static class SingletonFactory {
        private final static ModleManage instance = new ModleManage();
    }
    
	@SuppressWarnings("unchecked")
	private InfDateManageIfe<Long, TbUserModle> tbUserManage = (InfDateManageIfe<Long, TbUserModle>) getProxy(new InfDateManage<Long, TbUserModle>(TbUserModle.class));
	
    
    public Object getProxy(Object obj){  	
    	return (Object) Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), new ModleHandle(obj));
    }
    
    public InfDateManageIfe<Long, TbUserModle> getTbUserManage() {
		return tbUserManage;
	}
    
    @Override
    public void run() {
		while(true) {
			ConcurrentMap<Long,TbUserModle> tbUserMap = tbUserManage.getCatch().asMap();
			Iterator<ConcurrentMap.Entry<Long,TbUserModle>> iteratorUserMap = tbUserMap.entrySet().iterator();
			while (iteratorUserMap.hasNext()) {
				ConcurrentMap.Entry<Long,TbUserModle> entry = iteratorUserMap.next();
				if(System.currentTimeMillis() - entry.getValue().getUpdateTime() > 1*30*1000) {
					 tbUserManage.getCatch().invalidate(entry.getKey());
					 tbUserManage.writeCatchToSql(entry.getValue());
					 System.out.println("remove cache key"+entry.getKey());
				}	
			}
			
			
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
